import router, { asyncRoutes } from './router';
import Vue from 'vue';
import { setTitle } from './utility/setPageTitle';
import store from './store/index';

//防止路由找不到时陷入死循环
let isAdd = true;

//路由守卫
//异步方式，和await配合，否则Promise异步获取菜单，会导致Home不能即时获取菜单数据
router.beforeEach(async function (to, from, next) {
    //设置页面标题
    document.title = setTitle(to.meta.title);

    //如果有tokne,说明不是匿名用户
    if (Vue.ls.get('token')) {
        if (to.path === '/login') {
            next("/")
        } else {
            let menuData = Vue.ls.get('menu');
            if (menuData == null) {
                var menu = await store.dispatch('GetMenu');

                Vue.ls.set('menu', menu)
                menuData = menu;
            }

            //路由有没有动态添加完成
            if (to.name == null && isAdd) {
                isAdd = false;

                //动态添加路由
                menuData.filter(m => m.menuType == 0).forEach(m => {
                    var currRoute = {
                        path: m.menuRoute,
                        name: m.menuCode,
                        meta: {
                            title: m.menuName
                        },
                        component: (resolve) => require(['@/views/' + m.componentPath], resolve),
                        children: []
                    };

                    menuData.filter(sub => sub.parentId == m.id).forEach(sub => {
                        currRoute.children.push({
                            path: sub.menuRoute,
                            name: sub.menuCode,
                            meta: {
                                title: sub.menuName
                            },
                            component: (resolve) => require(['@/views/' + sub.componentPath], resolve),
                        })
                    });

                    asyncRoutes.push(currRoute);
                });

                router.addRoutes(asyncRoutes);

                next({ ...to, replace: true })
            }
            else {
                //放行
                next();
            }
        }
    }
    else {
        if (to.path === "/login") {
            next()
        }
        else {
            next('/login')
        }
    }
})